import os
from PIL import Image
import piexif

from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

# 定义一个函数来遍历文件夹
def resize_images(directory, max_size_mb=4):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg')):  # 只处理图片文件
                file_path = os.path.join(root, file)
                file_size = os.path.getsize(file_path) / (1024 * 1024)  # 文件大小转换为MB
                if file_size > max_size_mb:
                    # 载入图片
                    with Image.open(file_path) as img:
                        # 读取EXIF信息
                        try:
                            exif_dict = piexif.load(img.info['exif']) if 'exif' in img.info else {}
                            exif_bytes = piexif.dump(exif_dict)

                            # 保存图片，逐步降低质量直到文件大小小于4MB
                            quality = 95  # 初始质量设置
                            while file_size > max_size_mb:
                                with open(file_path, 'wb') as f:
                                # with open('/mnt/data/resize_test.jpg', 'wb') as f:
                                    img.save(f, 'JPEG', quality=quality, exif=exif_bytes)
 
                                file_size = os.path.getsize(file_path) / (1024 * 1024)
                                quality -= 5  # 每次降低5的质量
                        # 保存最终调整后的图片，覆盖原文件
                            img.save(file_path, 'JPEG', quality=quality, exif=exif_bytes)
                            print(f"Resized and saved: {file_path}")

                        except OSError as e:
                            print(f"Error processing file {file_path}: {e}")
                            continue
# 调用函数，替换为你的目录
resize_images('pic')
